#include "DxGraphicsBuffer.h"
GraphicsBuffer ::GraphicsBuffer()
{
	_d3d = NULL;
	_d3ddev = NULL;
	_backbuffer = NULL;
}
GraphicsBuffer :: ~GraphicsBuffer()
{
	_backbuffer->Release();
	_d3d->Release();
	_d3ddev->Release();
}
bool GraphicsBuffer::Inint_Direct3D(HWND hwnd, int width,int height)
{
	_d3d = Direct3DCreate9(D3D_SDK_VERSION);
	if(_d3d == NULL)
	{
		MessageBox(hwnd , "Loi khoi tao Direct3D" , "Error",MB_OK);
		return false;
	}

	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp,sizeof(d3dpp));
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
	d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferWidth = width;
	d3dpp.hDeviceWindow = hwnd;

	if(FAILED(_d3d->CreateDevice(	D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		hwnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp,
		&_d3ddev)))
	{
		MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK);
		return false;
	}

	_d3ddev->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1.0f,0);

	_d3ddev->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO, &_backbuffer);

	return true;
}
LPDIRECT3DSURFACE9 GraphicsBuffer ::LoadSuface(char * fileName, D3DCOLOR transColor)
{
	LPDIRECT3DSURFACE9 image = NULL;
	D3DXIMAGE_INFO info;
	HRESULT result;

	result = D3DXGetImageInfoFromFile(fileName,&info);

	if(result != D3D_OK)
		return NULL;

	result = D3DXLoadSurfaceFromFile(image,
		NULL,
		NULL,
		fileName,
		NULL,
		D3DX_DEFAULT,
		0,
		NULL);
	if (result != D3D_OK)
		return NULL;

	return image;
}
void GraphicsBuffer ::BeginRender(HWND hwnd, LPDIRECT3DSURFACE9 background)
{
	if (_d3ddev == NULL)
		return ;
	RECT srcR;
	srcR.top = srcR.left = 0;
	srcR.right = srcR.left + WINDOW_WIDTH;
	srcR.bottom = srcR.top + WINDOW_HEIGHT;
	_d3ddev->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1.0f,0);
	if(!_d3ddev->BeginScene())
		_d3ddev->StretchRect(background,NULL,_backbuffer,&srcR,D3DTEXF_NONE);
}

void GraphicsBuffer::EndRender()
{
	_d3ddev->EndScene();
	_d3ddev->Present(NULL,NULL,NULL,NULL);

}